import 'dart:convert';

import 'package:agent_process_app/utils/myUtils.dart' as myUtils;
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

//main() => runApp(new MyApp());

//源码注释 : 在整个应用程序中唯一的键。
final GlobalKey<ScaffoldState> _scaffoldstate = GlobalKey<ScaffoldState>();

//class LoginScreen extends StatelessWidget {
//    String username;
//
//    @override
//    Widget build(BuildContext context) {
//        return LoginHomePage();
//    }
//}

class LoginScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return Login();
  }
}

class Login extends State<LoginScreen> with TickerProviderStateMixin {
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();

  //在底部弹出的提示
  void _showSnackBar(String value) {
//    if(value.isEmpty) return;
    _scaffoldstate.currentState.showSnackBar(SnackBar(
      duration: Duration(milliseconds: 1000),
      content: Text(value),
    ));
  }

  Widget loginButton;

  Color _loginButtonColor;

  AnimationController controller1;
  AnimationController controller2;
  AnimationController controller3;
  Animation<double> opacityVal1; //透明度

  Animation<double> opacityVal2; //透明度

  Animation<double> opacityVal3; //透明度

  @override
  initState() {
    super.initState();
    controller1 = new AnimationController(
        duration: const Duration(milliseconds: 3000), vsync: this);
    // 透明度动画
    opacityVal1 = new Tween(begin: 0.0, end: 1.0).animate(controller1)
      ..addListener(() {
        setState(() {});
      });

    controller2 = new AnimationController(
        duration: const Duration(milliseconds: 2000), vsync: this);
    // 透明度动画
    opacityVal2 = new Tween(begin: 0.0, end: 1.0).animate(controller2)
      ..addListener(() {
        setState(() {});
      });

    controller3 = new AnimationController(
        duration: const Duration(milliseconds: 2000), vsync: this);
    // 透明度动画
    opacityVal3 = new Tween(begin: 0.0, end: 1.0).animate(controller3)
      ..addListener(() {
        setState(() {});
      });
    controller1.forward();

    Future.delayed(new Duration(seconds: 1), () {
      controller2.forward();
    });

    Future.delayed(new Duration(seconds: 2), () {
      controller3.forward();
    });
  }

  @override
  Widget build(BuildContext context) {
    showLoading() {
      print("登录中");
      setState(() {
        loginButton = RaisedButton(
          onPressed: () {
            _showSnackBar('登录中');
          },
          child: CircularProgressIndicator(
              valueColor:
                  AlwaysStoppedAnimation(Theme.of(context).canvasColor)),
          color: _loginButtonColor != null
              ? _loginButtonColor
              : Theme.of(context).primaryColor,
        );
      });
    }

    _httpClient() async {
      showLoading();
      String username = _usernameController.text;
      String password = _passwordController.text;
      //获取password的Base64加密后的值
      var passwordBytes = utf8.encode(password);
      var passwordBase64 = base64Encode(passwordBytes);
      FormData formData = new FormData.from({
        "username": username,
        "password": passwordBase64,
      });

      Dio dio = myUtils.MyDio.getDio("");
      Response response = await dio.post("/login", data: formData);

      int resCode = response.data["Code"];
      Map<String, dynamic> resData = response.data["Data"];
      print("登录时获取到的token=" + resData["token"]);
      print(resData["userInfo"]);
      //2019年2月10日 14:37:03 写到这里,写处理的逻辑
      if (resCode == 200) {
        //正确
        if (resData.isNotEmpty) {
          //将token持久化
          await myUtils.LocalStorage.getLocalStorageInstance()
              .then((SharedPreferences sharedPreferences) {
            sharedPreferences.setString("token", resData["token"]);
          });
          //userId
          await myUtils.LocalStorage.getLocalStorageInstance()
              .then((SharedPreferences sharedPreferences) {
            sharedPreferences.setInt("userId", resData["userInfo"]["Id"]);
          });
          //将username持久化
          await myUtils.LocalStorage.getLocalStorageInstance()
              .then((SharedPreferences sharedPreferences) {
            sharedPreferences.setString(
                "userName", resData["userInfo"]["Username"]);
          });
          //将nickName持久化
          await myUtils.LocalStorage.getLocalStorageInstance()
              .then((SharedPreferences sharedPreferences) {
            sharedPreferences.setString(
                "nickName", resData["userInfo"]["Nickname"]);
          });
          //将头像url持久化
          await myUtils.LocalStorage.getLocalStorageInstance()
              .then((SharedPreferences sharedPreferences) {
            sharedPreferences.setString(
                "imgUrl", resData["userInfo"]["ImgUrl"]);
          });
          //将角色持久化
          await myUtils.LocalStorage.getLocalStorageInstance()
              .then((SharedPreferences sharedPreferences) {
            sharedPreferences.setString("role", resData["userInfo"]["Role"]);
          });
          //根据不同的角色,跳转不同的主页面

          //登录成功,跳转主页面
          Navigator.of(context)
              .pushNamedAndRemoveUntil("/mainScreen", (route) => route == null);
        }
      } else if (resCode == 405) {
        //密码错误
        _showSnackBar("账户或密码错误!");
        setState(() {
          _loginButtonColor = Theme.of(context).errorColor;
        });
      } else if (resCode == 500) {
        //出异常了
        _showSnackBar("对不起,操作异常!");
        setState(() {
          _loginButtonColor = Theme.of(context).errorColor;
        });
      } else {
        _showSnackBar("请登录!");
        setState(() {
          _loginButtonColor = Theme.of(context).errorColor;
        });
      }
      //更新数据
      setState(() {
        loginButton = null; //将按钮恢复原来状态
      });
    }

    void login() async {
      String username = _usernameController.text;
      String password = _passwordController.text;
      if (username.isEmpty || password.isEmpty) {
        _showSnackBar("请输入用户名或密码!");
        return;
      }
      if (password.length < 6) {
        _showSnackBar("密码不能小于6位!");
        return;
      }
      //发送登录请求,同步执行登录请求.
      try {
        await _httpClient();
      } catch (e) {
        print(e);
        _showSnackBar("请检查您的网络是否正常!");
        setState(() {
          loginButton = null; //将按钮恢复原来状态
        });
      }
    }

    return Scaffold(
      key: _scaffoldstate,
      body: SingleChildScrollView(
        child: Center(
            child: Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                  padding: const EdgeInsets.only(top: 60.0, bottom: 20.0),
                  child: Opacity(
                    opacity: opacityVal1.value,
                    child: Image.asset(
                      'images/logo_text.png',
                      width: 160.0,
                    ),
                  )),
              Container(
                padding: const EdgeInsets.all(20.0),
                child: Opacity(
                  opacity: opacityVal1.value,
                  child: SizedBox(
                    width: double.infinity,
                    height: 50.0,
                    child: TextField(
                      controller: _usernameController,
                      decoration: InputDecoration(
                        icon: Icon(Icons.person_outline),
                        labelText: "用户名",
                        suffixIcon: IconButton(
                            icon: Icon(Icons.clear),
                            onPressed: () {
                              _usernameController.clear();
                            }), //输入框内右侧图标
                      ),
                    ),
                  ),
                ),
              ),
              Container(
                padding: const EdgeInsets.all(20.0),
                child: Opacity(
                  opacity: opacityVal2.value,
                  child: SizedBox(
                    width: double.infinity,
                    height: 50.0,
                    child: TextField(
                      onSubmitted: (text) {
                        login();
                      },
                      controller: _passwordController,
                      obscureText: true,
                      //让输入的内容变成圆点,输入密码场景中适用
                      decoration: InputDecoration(
                        icon: Icon(Icons.lock_outline),
                        labelText: "密码",
                        suffixIcon: IconButton(
                            icon: Icon(Icons.clear),
                            onPressed: () {
                              _passwordController.clear();
                            }), //输入框内右侧图标
                      ),
                    ),
                  ),
                ),
              ),
              Container(
                padding: const EdgeInsets.fromLTRB(40.0, 40.0, 40.0, 20.0),
                child: Opacity(
                  opacity: opacityVal3.value,
                  child: SizedBox(
                    width: double.infinity,
                    height: 50.0,
                    child: loginButton != null
                        ? loginButton
                        : RaisedButton(
                            onPressed: () {
                              login();
                            },
                            child: Text(
                              '登录',
                              style: TextStyle(
                                  color: Theme.of(context).canvasColor,
                                  fontSize: 20.0),
                            ),
                            color: _loginButtonColor != null
                                ? _loginButtonColor
                                : Theme.of(context).primaryColor,
//                      color: ThemeData.light().primaryColor,
                          ),
                  ),
                ),
              ),
            ],
          ),
        )),
      ),
    );
  }
}
